﻿using System;
using System.Windows;
using UnitFundProfitability.BusinessLogic;

namespace UnitFundProfitability
{
	/// <summary>
	/// Interaction logic for Incomes.xaml
	/// </summary>
	public partial class Incomes : Window
	{
		#region Constructors
		public Incomes()
		{
			InitializeComponent();
			ExistingUnitFunds.DataContext = Manager.Instance.GetUnitFunds();
			IncomeDate.SelectedDate = DateTime.Today.AddDays(-1);
			AddIncome.Click += new RoutedEventHandler(AddIncome_Click);
		}
		#endregion

		#region Methods
		private void AddIncome_Click(object sender, RoutedEventArgs e)
		{
			UnitFund selectedUnitFund = ExistingUnitFunds.SelectedValue as UnitFund;
			if (selectedUnitFund == null)
			{
				MessageBox.Show("Please, select unit fund.", "Select unit fund");
			}
			else if (!IncomeDate.SelectedDate.HasValue)
			{
				MessageBox.Show("Please, select date.", "Select date");
			}
			else
			{
				decimal moneyAmount = 0;
				decimal unitsAmount = 0;
				if ((!string.IsNullOrWhiteSpace(MoneyAmount.Text) && !decimal.TryParse(MoneyAmount.Text, out moneyAmount)) || moneyAmount < 0)
				{
					MessageBox.Show("Please, enter a valid money amount.", "Invalid number");
				}
				else if ((!string.IsNullOrWhiteSpace(UnitsAmount.Text) && !decimal.TryParse(UnitsAmount.Text, out unitsAmount)) || unitsAmount < 0)
				{
					MessageBox.Show("Please, enter a valid units amount.", "Invalid number");
				}
				else if ((moneyAmount == 0 && unitsAmount == 0) || (moneyAmount != 0 && unitsAmount != 0))
				{
					MessageBox.Show("Money amount or units amount should be equal to zero, but one of them should not be equal to zero.", "Invalid input");
				}
				else
				{
					Income income = new Income();
					income.FundId = selectedUnitFund.FundId;
					income.MoneyAmount = moneyAmount;
					income.UnitsAmount = unitsAmount;
					Manager.Instance.AddIncome(income, IncomeDate.SelectedDate.Value);
				}
			}
		}
		#endregion
	}
}